import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html/style.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/home/api/api_home.dart';
import 'package:tender_flutter/page/home/model/market_contact_entity_entity.dart';
import 'package:tender_flutter/page/home/model/market_detail_entity.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';
import 'package:tender_flutter/widgets/net_image.dart';
import 'package:url_launcher/url_launcher.dart';

class MarketDetailPage extends StatefulWidget {
  @override
  _MarketDetailPageState createState() => _MarketDetailPageState();
}

class _MarketDetailPageState extends State<MarketDetailPage> {
  /// 供需id（由参数传递）
  String marketId;

  MarketDetailEntity _detailEntity;

  MarketContactEntity _contactEntity;

  LoadState _loadState = LoadState.State_Loading;

  /// 获取联系方式
  Future<MarketContactEntity> _getContact() async {
    if (_contactEntity != null) {
      return _contactEntity;
    }
    ToastUtils.showLoading("");
    var response = await ApiHome.getMarketContact<MarketContactEntity>(
        int.parse(marketId));
    ToastUtils.dismissLoading();
    _contactEntity = response.result;
    return _contactEntity;
  }

  /// 获取详情
  Future<ApiResponse<MarketDetailEntity>> _getDetail() async {
    marketId = RouteData.of(context).queryParams["marketId"].stringValue;
    return await ApiHome.getMarketDetail(int.parse(marketId));
  }

  FutureBuilder<ApiResponse<MarketDetailEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _getDetail(),
        // ignore: missing_return
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<MarketDetailEntity>> snapshot) {
          if (snapshot.hasData) {
            _detailEntity = snapshot.data.result;
            _loadState = LoadState.State_Success;
            return LoadStateLayout(
              state: _loadState,
              bgColor: ThemeColors.colorWhite,
              successWidget: _initBody(),
            );
          } else {
            return LoadStateLayout(
              bgColor: ThemeColors.colorWhite,
              state: _loadState,
            );
          }

          _loadState = LoadState.State_Loading;
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: ThemeColors.colorWhite,
        appBar: _initAppBar(),
        body: _buildFutureBuilder());
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(context, Text("详情", style: FonStyle.navTextStyle()));
  }

  /// 内容提
  Widget _initBody() {
    return Column(children: [
      Expanded(
          child: Container(
              child: SingleChildScrollView(
        padding: EdgeInsets.all(ScreenAdapter.width(30)),
        physics: BouncingScrollPhysics(),
        child: Column(
          children: <Widget>[
            Container(
                width: double.infinity,
                child: Text(
                  _detailEntity.title,
                  textAlign: TextAlign.left,
                  style: TextStyle(
                      color: ThemeColors.colorType1,
                      fontSize: ScreenAdapter.sp(34),
                      fontWeight: FontWeight.bold),
                )),
            SizedBox(height: ScreenAdapter.height(15)),
            // Text(_detailEntity.content,
            //     style: TextStyle(
            //         color: ThemeColors.colorType1,
            //         fontSize: ScreenAdapter.sp(30))),
            Html(
              shrinkWrap: true,
              data: _detailEntity.content,
              style: {
                "html": Style(
                    backgroundColor: Colors.white,
                    fontSize: FontSize(ScreenAdapter.sp(32))
//              color: Colors.white,
                    ),
              },
              onLinkTap: (url) {
                // open url in a webview
                // ToastUtils.show("点击了链接$url");
              },
              onImageTap: (src) {
                // Display the image in large form.
              },
            ),
            ListView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: _detailEntity.pics.length,
                itemBuilder: (context, index) {
                  return _getImageItem(
                      context, index, _detailEntity.pics[index]);
                }),
            _getInfoItem("联系人", _detailEntity.name),
            _getInfoItem("公司名称", _detailEntity.company),
          ],
        ),
      ))),
      _initBottomLayout()
    ]);
  }

  /// 底部按钮试图
  Widget _initBottomLayout() {
    return Container(
        height: ScreenAdapter.height(100),
        child: Row(children: [
          Expanded(
              child: FlatButton(
                  onPressed: () {
                    // if (!isEmpty(_detailEntity.wx)) {
                    //   Clipboard.setData(
                    //       new ClipboardData(text: _detailEntity.wx));
                    //   ToastUtils.show("复制成功");
                    //   Future.delayed(Duration(milliseconds: 400), () async {
                    //     String url = "weixin://";
                    //     if (await canLaunch(url)) {
                    //       await launch(url);
                    //     } else {
                    //       throw 'Could not launch $url';
                    //     }
                    //   });
                    // } else {
                    //   ToastUtils.show("微信账号异常");
                    // }
                    _getContact().then((value) {
                      if (value != null) {
                        Clipboard.setData(new ClipboardData(text: value.wx));
                        ToastUtils.show("复制成功");
                        Future.delayed(Duration(milliseconds: 400), () async {
                          String url = "weixin://";
                          if (await canLaunch(url)) {
                            await launch(url);
                          } else {
                            throw 'Could not launch $url';
                          }
                        });
                      } else {
                        ToastUtils.show("微信账号异常");
                      }
                    });
                  },
                  height: double.infinity,
                  color: ThemeColors.colorType42,
                  shape: RoundedRectangleBorder(),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(RPath.imgPath + "icon_wecha_white.png",
                          fit: BoxFit.contain,
                          width: ScreenAdapter.width(44),
                          height: ScreenAdapter.width(44)),
                      Text("  微信联系",
                          style: TextStyle(
                              fontSize: ScreenAdapter.sp(30),
                              color: ThemeColors.colorWhite))
                    ],
                  ))),
          Expanded(
              child: FlatButton(
                  onPressed: () {
                    _getContact().then((value) => {
                          if (value != null)
                            {launch("tel:" + value.phone ?? "")}
                        });
                  },
                  height: double.infinity,
                  color: ThemeColors.colorType6,
                  shape: RoundedRectangleBorder(),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(RPath.imgPath + "icon_tel_white.png",
                          fit: BoxFit.contain,
                          width: ScreenAdapter.width(35),
                          height: ScreenAdapter.width(35)),
                      Text("  拨打电话",
                          style: TextStyle(
                              fontSize: ScreenAdapter.sp(30),
                              color: ThemeColors.colorWhite))
                    ],
                  )))
        ]));
  }

  Widget _getInfoItem(String title, String content) {
    return Container(
        margin: EdgeInsets.symmetric(vertical: ScreenAdapter.height(15)),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
                margin: EdgeInsets.only(
                    top: ScreenAdapter.height(8),
                    right: ScreenAdapter.width(15)),
                height: ScreenAdapter.height(20),
                width: ScreenAdapter.width(4),
                color: ThemeColors.colorType6),
            Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(title,
                      style: TextStyle(
                          color: ThemeColors.colorType1,
                          fontSize: ScreenAdapter.sp(30),
                          fontWeight: FontWeight.bold)),
                  SizedBox(height: ScreenAdapter.height(10)),
                  Text(content,
                      style: TextStyle(
                          color: ThemeColors.colorType1,
                          fontSize: ScreenAdapter.sp(30))),
                ])
          ],
        ));
  }

  /// 图片Item
  Widget _getImageItem(BuildContext context, int index, String imgUrl) {
    return GestureDetector(
        onTap: () {
          LRouter.navigatorCtx(context).push(Routes.imageBrowsePage,
              arguments: ImageBrowsePageArguments(
                  images: _detailEntity.pics, currentIndex: index));
        },
        child: Container(
            margin: EdgeInsets.symmetric(vertical: ScreenAdapter.height(15)),
            child: MyNetImage(
                // width: ScreenAdapter.screenWidth(),
                // height: ScreenAdapter.height(300),
                url: imgUrl,
                radius: BorderRadius.circular(ScreenAdapter.width(5)))));
  }
}
